package com.qf.commons.web.exception;

import com.qf.commons.data.result.R;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 用于处理响应体的问题
 * 例如：处理返回给客户端状态码的问题
 * @author YaoJiXing
 * created 2022/8/19 16:13
 */
@RestControllerAdvice
public class ResponseHandler implements ResponseBodyAdvice {

    /**
     * supports 方法如果返回true beforeBodyWrite 方法才会执行
     * ???
     * @param methodParameter
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        //System.out.println(methodParameter.getMethod());
        return methodParameter.getMethod().getReturnType() == R.class;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        R result = (R) o;
        if (result.getCode() != 200) {
            //处理响应的结果未成功，改变响应的状态码
            //INTERNAL_SERVER_ERROR - 内部服务器错误
            serverHttpResponse.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return result;
    }
}
